package wireless.util;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cm.util.action.list.GenericListActionSupport;
import cm.util.hibernate.HibernateSessionFactory;

/**
 * save and get from mysql
 * @author miracle
 * 2012-11-13
 */
public class GetAndSave<E> {

	    private String hql;
	    private Query query;
	    private E entity;
	    private static Log log=LogFactory.getLog(GenericListActionSupport.class);
	    /* 
	     * 构造函数
	     */
	    @SuppressWarnings("unchecked")
		public GetAndSave(String entityClassName){
	    	try{
				/**
				 * 初始化实体对象
				 */
				entity=(E)Class.forName(entityClassName).newInstance();
				
			} catch (ClassNotFoundException e){
				log.error("不存在名为:"+entityClassName+"的类！", e);
			} catch (InstantiationException e) {
				log.error("实例化"+entityClassName+"对象出错！", e);
			} catch (IllegalAccessException e) {
				log.error(e);
			}
	    	
	    }
	    public Session getSession() {
			return HibernateSessionFactory.getSession();

		}
		public List<E>  getEntityList(){
			try {
			hql = "from "+entity+" as f where f.length=4";
			query = getSession().createQuery(hql);
			return query.list();
			} catch (RuntimeException re) {
				throw re;
			}
		}
	/**	
	 * 批量存入数据库
	 * @param list
	 * @return
	 */
		@SuppressWarnings("unchecked")
		public String saveEntityList(List<E> list){
			Session session = getSession();
			Transaction tx = session.beginTransaction();
			 
			try {
				//hql = "";
				//query = getSession().createQuery(hql);
				for(Iterator sit=list.iterator();sit.hasNext();)//迭代取值
			     {
					 E entity=(E)sit.next();
					 session.save(entity);
			     }	
				 session.flush();
	             session.clear();
	             tx.commit();
				return "success";
			} catch (RuntimeException re) {
				// TODO: handle exception
				re.printStackTrace();
	            tx.rollback();
	            throw re;
			
			}finally{
	            session.close();
	        }
		}
	}

	

